package ar.com.android.restoapp.forms;

import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import ar.com.android.restoapp.forms.R;
import ar.com.android.restoapp.http.CustomHttpClient;
import ar.com.android.restoapp.utils.AppGlobalVariables;
import ar.com.android.restoapp.utils.Constants;
import ar.com.android.restoapp.utils.MCrypt;
import ar.com.android.restoapp.utils.SyncDatabase;

public class LoginActivity extends Activity implements Runnable
{
	
	private static final String TAG = "LoginActivity";
	
	private static final int iLoginIncorrect = 1;
	private static final int iDBErrorConect = -1;
	private static final int iLoginGrant = 0;
	
	//Defined Object Form and LogTag
	EditText etUserName, etPassword;
	Button butLogin;
	
	ProgressDialog dialog;
	
    /** Called when the activity is first created. */
    @Override
    public void onStart()
    {
    	super.onStart();
    	((EditText)findViewById(R.id.etUserName)).requestFocus();
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        setTitle(getString(R.string.app_name) + " - " + getString(R.string.loginTitle));
        
        ((EditText)findViewById(R.id.etUserName)).requestFocus();
    }
    
    public void clearForm()
    {
    	((EditText)findViewById(R.id.etUserName)).setText("");
    	((EditText)findViewById(R.id.etPassword)).setText("");
    }
    
    public void onClickLogin(View v) throws Exception
    {
    	etUserName = (EditText) findViewById(R.id.etUserName);
    	etPassword = (EditText) findViewById(R.id.etPassword);
    	
    	if(etUserName.getText().toString().equals("")) {
			LayoutInflater inflater = getLayoutInflater();
			View layout = inflater.inflate(R.drawable.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

			TextView text = (TextView) layout.findViewById(R.id.text);
			text.setText(getText(R.string.userRequired));

			Toast toast = new Toast(getApplicationContext());
			toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			toast.setDuration(Toast.LENGTH_LONG);
			toast.setView(layout);
			toast.show();			
    	}
    	else if(etPassword.getText().toString().equals("")) {
			LayoutInflater inflater = getLayoutInflater();
			View layout = inflater.inflate(R.drawable.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

			TextView text = (TextView) layout.findViewById(R.id.text);
			text.setText(getText(R.string.passwordRequired));

			Toast toast = new Toast(getApplicationContext());
			toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			toast.setDuration(Toast.LENGTH_LONG);
			toast.setView(layout);
			toast.show();				
    	}
    	else
    	{
    		dialog = ProgressDialog.show(LoginActivity.this, "", getString(R.string.loadingMessagge), true);
    		Thread thread = new Thread(this);
    		thread.start();
    	}
    }

	@Override
	public void run() {
		Looper.myLooper(); 
	    Looper.prepare();
	    
		try {
			MCrypt encryptAES = new MCrypt();
			String encryptPass = MCrypt.bytesToHex(encryptAES.encrypt(etPassword.getText().toString()));
			
			ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
			postParameters.add(new BasicNameValuePair("action", "validateUser"));
			postParameters.add(new BasicNameValuePair("userName", etUserName.getText().toString()));
			postParameters.add(new BasicNameValuePair("userPassword", encryptPass));
			
			String response = CustomHttpClient.executeHttpPost(Constants.URL_SERVER_UTILS, postParameters);
			JSONObject jsonUser = new JSONObject(response);
			
			if(jsonUser.getString("permission").equals("DENIED")) {
				Message msg = Message.obtain(); 
                msg.what = iLoginIncorrect; 
                msg.obj = jsonUser.getString("permission"); 
                handler.sendMessage(msg);                 
			}
			else if(jsonUser.getString("permission").equals("GRANT"))
			{
				AppGlobalVariables.getInstance().setUserName(jsonUser.getString("userName"));
				AppGlobalVariables.getInstance().setUserCompleteName(jsonUser.getString("userCompleteName"));
				AppGlobalVariables.getInstance().setUserEMail(jsonUser.getString("userEMail"));
				AppGlobalVariables.getInstance().setIdUser(Integer.parseInt(jsonUser.getString("idUser")));
				AppGlobalVariables.getInstance().setIdRestaurant(Integer.parseInt(jsonUser.getString("idRestaurant")));

				SyncDatabase.syncDatabaseFood(this);
				
				Message msg = Message.obtain(); 
                msg.what = iLoginGrant; 
                msg.obj = jsonUser.getString("permission"); 
                handler.sendMessage(msg);  
			}
		} catch (Exception e) {
			e.printStackTrace();
			Log.e(TAG, e.getMessage());
			Message msg = Message.obtain();
            msg.what = iDBErrorConect; 
            msg.obj = e; 
            handler.sendMessage(msg);
		}
	}
	
	private void updateActivity(Message msg)
	{
		if (msg.what == iLoginIncorrect) { 
			LayoutInflater inflater = getLayoutInflater();
			View layout = inflater.inflate(R.drawable.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

			TextView text = (TextView) layout.findViewById(R.id.text);
			text.setText(getText(R.string.incorrectLogin));

			Toast toast = new Toast(getApplicationContext());
			toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			toast.setDuration(Toast.LENGTH_LONG);
			toast.setView(layout);
			toast.show();
		}
		else if (msg.what == iDBErrorConect) { 
			LayoutInflater inflater = getLayoutInflater();
			View layout = inflater.inflate(R.drawable.toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));

			TextView text = (TextView) layout.findViewById(R.id.text);
			text.setText(getText(R.string.errorDBLogin));

			Toast toast = new Toast(getApplicationContext());
			toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
			toast.setDuration(Toast.LENGTH_LONG);
			toast.setView(layout);
			toast.show();
		}
		else {
			Intent intentMenu = new Intent(this, MenuActivity.class);
    		startActivityForResult(intentMenu, 1);
    		clearForm();
		}
		dialog.dismiss();
	}
	
	private Handler handler = new Handler() {
	        @Override
	        public void handleMessage(Message msg) {
	        	updateActivity(msg);
	        }
	};
}